package net.khoroshev.dveri.dao;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyFactory;

public abstract class BaseDao<T> {
	protected ObjectifyFactory ofyf;
	
	public T get(Long id) {
		Key<T> key = (Key<T>) Key.create(objClass(), id);
		return ofyf.begin().load().key(key).get();
	}
	
	public Iterable<T> getAll() {
		return ofyf.begin().load().type(objClass()).iterable();
	}
	
	public BaseDao<T> save(T obj){
		ofyf.begin().save().entity(obj).now();
		return this;
	}
	
	public BaseDao<T> delete(T obj){
		ofyf.begin().delete().entity(obj).now();
		return this;
	}

	public int getCount() {
		return ofyf.begin().load().type(objClass()).count();
	}
	
	protected abstract T getObjectExample();
	
	public BaseDao(ObjectifyFactory ofyf) {
		this.ofyf = ofyf;
		ofyf.register(objClass());
	}

	@SuppressWarnings("unchecked")
	private Class<T> objClass() {
		return  (Class<T>) getObjectExample().getClass();
	}
}
